<template>
    <el-dialog
        :title="title + '方案'"
        :visible.sync="showValue"
        append-to-body
        :close-on-click-modal="false"
        fullscreen
        :before-close="clearData"
    >
        <el-form
            ref="form"
            :model="form"
            :rules="rules"
            inline
            size="small"
            label-width="150px"
        >
            <el-form-item label="经营类型：" prop="managementTypes">
                <el-select
                    class="formItem"
                    @change="clearCompany"
                    v-model="form.managementTypes"
                    placeholder="请选择"
                    size="small"
                >
                    <el-option
                        v-for="(item, index) in managementTypeList"
                        :key="index"
                        :label="item.value"
                        :value="item.key"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="服务：" prop="addServiceCodes">
                <div class="flex">
                    <div class="oe">{{ serveObjList }}</div>
                    <el-button
                        size="mini"
                        @click="setServe"
                        type="primary"
                        plain
                        >选择</el-button
                    >
                </div>
            </el-form-item>
            <el-form-item label="方案名称：" prop="schemeName">
                <el-input
                    class="formItem"
                    placeholder="请输入方案名称"
                    v-model="form.schemeName"
                ></el-input>
            </el-form-item>

            <el-form-item label="状态：" prop="status">
                <el-select
                    class="formItem"
                    v-model="form.status"
                    placeholder="请选择"
                    size="small"
                >
                    <el-option label="启用" :value="1"></el-option>
                    <el-option label="停用" :value="0"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="是否针对所有商家：" prop="allCompany">
                <el-select
                    class="formItem"
                    v-model="form.allCompany"
                    placeholder="请选择"
                    size="small"
                >
                    <el-option label="是" :value="1"></el-option>
                    <el-option label="否" :value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                label="指定商家："
                v-if="form.allCompany === 0"
                prop="companyIDs"
            >
                <el-button size="mini" @click="addCompany" type="primary" plain
                    >配置商家</el-button
                >
            </el-form-item>
            <el-form-item label="方案描述：" prop="description">
                <el-input
                    class="formItem"
                    placeholder="请输入方案描述"
                    v-model="form.description"
                ></el-input>
            </el-form-item>
        </el-form>
        <div class="row 100w" style="height: 50px; line-height: 50px">
            <div class="left item">
                <span> <span class="tip"> * </span>充值规则:</span>
                <!-- <span class="tip" v-show="currServeObj.marketPrice"
                    >建议最低金额不能低于{{
                        currServeObj.marketPrice
                    }}元，最高金额不能高于{{
                        currServeObj.originalPrice
                    }}元</span
                > -->
            </div>
            <div class="col right item">
                <el-button type="primary" size="mini" plain @click="addRule"
                    >添加规则</el-button
                >
            </div>
        </div>

        <el-table
            :header-cell-style="headerCellStyle"
            :data="form.rules"
            style="width: 100%"
            border
            stripe
            size="mini"
        >
            <el-table-column align="center" prop="price" label="收费(元)">
                <template slot-scope="scope">
                    <input-m
                        align="center"
                        style="width: 100px"
                        :word.sync="scope.row.price"
                    ></input-m>
                </template>
            </el-table-column>
            <el-table-column prop="buyDays" align="center" label="购买天数">
                <template slot-scope="scope">
                    <el-input-number
                        size="mini"
                        :controls="false"
                        @focus="focus($event)"
                        v-model="scope.row.buyDays"
                        style="width: 100px"
                        :min="1"
                    ></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="giftDays" align="center" label="赠送天数">
                <template slot-scope="scope">
                    <el-input-number
                        size="mini"
                        :controls="false"
                        @focus="focus($event)"
                        v-model="scope.row.giftDays"
                        style="width: 100px"
                        :min="0"
                    ></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="status" align="center" label="状态">
                <template slot-scope="scope">
                    <el-switch
                        :active-value="1"
                        :inactive-value="0"
                        v-model="scope.row.status"
                    >
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column prop="msg" align="center" label="提示">
                <template slot-scope="scope">
                    <span class="tip">{{ scope.row.msg }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="date"
                align="center"
                label="操作"
                width="80px"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        plain
                        class="el-button-10"
                        @click="deleteRule(scope.$index)"
                        type="danger"
                        >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="save"
                >保 存</el-button
            >
        </div>
        <addCompany
            :form="form"
            :value.sync="showTree"
            :checkArr="form.companyIDs"
            @getIds="getIds"
        ></addCompany>
        <checkServe
            :form="form"
            :arr="form.addServiceCodes"
            :serveList="serveList"
            :value.sync="isShowSetServe"
            @setServeIds="setServeIds"
        ></checkServe>
    </el-dialog>
</template>

<script>
import addCompany from './addCompany'
import checkServe from './checkServe'
export default {
    components: {
        addCompany,
        checkServe
    },
    props: {
        value: Boolean,
        currType: Number,
        currRow: Object
    },
    data () {
        return {
            isShowSetServe: false,
            copyData: [],
            copyData1: '',
            checkArr: [],
            showTree: false,
            title: '',
            rules: {
                addServiceCodes: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                managementTypes: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                allCompany: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                schemeName: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                status: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                companyIDs: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                rules: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ]
            },
            managementTypeList: [], // 经营类型列表
            form: {
                description: '',
                addServiceCodes: [], // 服务
                managementTypes: '', // 经营类型
                allCompany: 1, // 是否针对所有商家,0否1是
                schemeName: '', // 方案名称
                status: 1, // 启用,停用
                companyIDs: [], // 适用商家列表
                rules: [] // 充值规则列表
            },
            loading: false,
            showValue: false,
            data: [],
            serveList: [],
            serveObjList: '',
            plan: [
                {
                    pay: '',
                    messageNum: '',
                    presentNum: '',
                    price: 0,
                    sort: '',
                    time: '2020-12-12 12:12:12'
                }
            ]
        }
    },
    watch: {
        value (val) {
            this.showValue = val
            if (val) {
                this.getTitle()
                this.getManagementList()
                if (this.currRow.schemeID) {
                    this.getDetail()
                } else {
                    this.addPlan()
                }
            }
        },
        showValue (val) {
            this.$emit('update:value', val)
        },
        'form.addServiceCodes': {
            deep: true,
            handler: function (newV, oldV) {
                this.copyData = oldV
            }
        },
        'form.managementTypes': {
            deep: true,
            handler: function (newV, oldV) {
                console.log(oldV)
                this.copyData1 = oldV
            }
        }
    },
    created () {

    },
    methods: {
        async getDetail () {
            let res = await this.$axios.post(this.$store.state.ip + '/server/admin/serverinfo/info', {
                data: {
                    schemeID: this.currRow.schemeID
                }
            })
            let response = res.data
            if (response.ret === '0') {
                this.form = response.data
                this.form.managementTypes = Number(response.data.platform)
                this.form.addServiceCodes = response.data.addServiceCodes.split(',')
                if (!this.form.rules) {
                    this.form.rules = []
                }
                this.serveObjList = this.form.addServiceNames
                this.getServeList()
            }
        },
        setServeIds (ids, arr) {
            console.log(ids)
            console.log(arr)
            this.form.addServiceCodes = ids
            this.serveObjList = arr
        },
        setServe () {
            if (!this.form.managementTypes) {
                return this.$message({
                    showClose: true,
                    message: '请先选择经营类型',
                    type: 'warning'
                })
            }
            if (this.serveList && this.serveList.length === 0) {
                return this.$message({
                    showClose: true,
                    message: '该经营类型无可用服务',
                    type: 'warning'
                })
            }
            if (this.form.allCompany === 1 || this.form.companyIDs.length === 0) {
                this.isShowSetServe = true
                return
            }
            this.$confirm('该操作会清空已选择的指定商家，是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.isShowSetServe = true
                this.form.allCompany = 1
                this.form.status = 1
                this.form.companyIDs = []
            }).catch(() => {
                // this.form.addServiceCode = this.copyData
            })
        },
        async getServeList () {
            let res = await this.$axios.post(this.$store.state.ip + '/server/agent/serverinfo/base/list', {
                data: {
                    platform: this.form.managementTypes,
                    agentId: this.$store.state.loginParams.agentId
                }
            })
            let response = res.data
            if (response.ret === '0') {
                this.serveList = response.data || []
            }
        },
        async getManagementList () {
            let res = await this.$axios.post(this.$store.state.ip + '/server/agent/management/list', {
                data: {}
            })
            let response = res.data
            if (response.ret === '0') {
                this.managementTypeList = response.data
            }
        },
        clearCompany (val) {
            this.getServeList()
            if (this.form.addServiceCodes.length === 0 && this.form.companyIDs.length === 0) {
                return
            }
            this.$confirm('该操作会清空已选择的服务和指定商家，是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.form.allCompany = 1
                this.form.status = 1
                this.form.companyIDs = []
                this.form.addServiceCodes = []
            }).catch(() => {
                this.form.managementTypes = this.copyData1
                this.getServeList()
            })
        },
        getIds (arr) {
            console.log(arr)
            this.form.companyIDs = arr
        },
        addCompany () {
            if (!this.form.managementTypes) {
                return this.$message({
                    showClose: true,
                    message: '请先选择经营类型',
                    type: 'warning'
                })
            }
            this.showTree = true
        },
        addRule () {
            this.form.rules.push(
                {
                    buyDays: null,
                    price: null,
                    giftDays: null,
                    msg: '',
                    status: 1
                }
            )
        },
        getTitle () {
            if (this.currType === 0) {
                this.title = '新增'
            }
            if (this.currType === 1) {
                this.title = '编辑'
            }
        },
        addPlan () {
            this.form = {
                description: '',
                addServiceCodes: [], // 服务
                managementTypes: '', // 经营类型
                allCompany: 1, // 是否针对所有商家,0否1是
                schemeName: '', // 方案名称
                status: 1, // 启用,停用
                companyIDs: [], // 适用商家列表
                rules: [] // 充值规则列表
            }
        },
        deleteRule (index) {
            this.form.rules.splice(index, 1)
        },
        saveShop () {
            this.showShop = false
        },
        focus (event) {
            event.currentTarget.select()
        },
        // 清空数据
        clearData () {
            this.serveObjList = ''
            this.form.rules = []
            this.$refs['form'].resetFields()
            this.loading = false
            this.showValue = false
        },
        // 保存表单
        save () {
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    let isDayTip = false
                    let isPriceTip = false
                    if (this.form.rules.length === 0) {
                        this.$message({
                            showClose: true,
                            message: '规则不能为空',
                            type: 'warning'
                        })
                        return
                    }
                    this.form.rules.forEach(item => {
                        if (item.buyDays + item.giftDays < 365) {
                            isDayTip = true
                        }
                        if (item.price <= 0) {
                            isPriceTip = true
                        }
                    })
                    if (isDayTip) {
                        this.$message({
                            showClose: true,
                            message: '购买天数+赠送天数不能小于365天',
                            type: 'warning'
                        })
                        return
                    }
                    if (isPriceTip) {
                        this.$message({
                            showClose: true,
                            message: '金额必须大于0，请参考提示金额',
                            type: 'warning'
                        })
                        return
                    }
                    this.loading = true
                    let res = await this.$axios.post(this.$store.state.ip + '/server/agent/serverinfo/save', {
                        data: {
                            ...this.form,
                            agentId: this.$store.state.loginParams.agentId,
                            agentName: this.$store.state.loginParams.agentName,
                            platform: this.form.managementTypes,
                            addServiceCodes: this.form.addServiceCodes.join(',')
                        }
                    })
                    let response = res.data
                    this.loading = false
                    if (response.ret === '0') {
                        this.$message({
                            message: '保存成功',
                            type: 'success'
                        })
                        this.$emit('getList')
                        this.clearData()
                    }
                    if (response.ret === '1002') {
                        this.$message({
                            message: response.msg,
                            type: 'warning'
                        })
                        response.data.forEach((item, i) => {
                            if (item.status === false) {
                                // this.form.rules[i].msg = item.msg
                                // this.$forceUpdate()
                                this.$set(this.form.rules[i], 'msg', item.msg)
                            }
                        })
                        console.log(this.form)
                    }
                }
            })
        }
    }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../../../../../../static/css/variables'

.el-transfer-panel
    width: 300px

.flex
    display: flex

.formItem
    width: 220px

.tip
    color: red

.oe
    max-width: 50px
    overflow: hidden // 超出的文本隐藏
    text-overflow: ellipsis // 溢出用省略号显示
    white-space: nowrap // 溢出不换行
</style>